<template>
  <div class="page">
    <div class="page-wrapper">
      <div class="header">
        {{ route.query.flag == 'updateOrder' ? '修改套餐' : '添加套餐' }}
      </div>
      <el-form
        ref="queryFormT"
        :rules="ruleT"
        :model="queryParams"
        :inline="true"
        label-width="80px"
      >
        <el-row>
          <el-form-item label="套餐名称" prop="mealName">
            <el-input
              maxlength="20"
              style="width: 180px"
              v-model="queryParams.mealName"
              placeholder="请输入套餐名称"
              clearable
              size="small"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <!-- <el-form-item label="服务单位" prop="orgId">
            <el-select
              style="width: 180px"
              v-model="queryParams.orgId"
              placeholder="请选择服务单位"
            >
              <el-option
                v-for="item in branchOfficeOptions"
                :key="item.codevalue"
                :label="item.codename"
                :value="item.codevalue"
              >
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="套餐价格" prop="amount">
            <el-input
              oninput="value=value.indexOf('.') > -1?value.slice(0, value.indexOf('.') + 3):value"
              type="number"
              style="width: 180px"
              v-model="queryParams.amount"
              placeholder="请输入套餐价格"
              clearable
              size="small"
            />
          </el-form-item>
        </el-row>
      </el-form>

      <el-button type="primary" size="small" icon="Plus" @click="addGoods"
        >新增套餐内容</el-button
      >
      <el-button
        type="danger"
        size="small"
        icon="Delete"
        @click="deleteGoods"
        :disabled="multiple"
        >删除套餐内容</el-button
      >
      <el-table
        show-summary
        :summary-method="getSummaries"
        :data="queryParams.mealLines"
        border
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          width="55"
        ></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="matName" label="商品名称" align="center" />
        <el-table-column prop="spec" label="商品规格" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="matNum" label="数量" align="center" />
        <el-table-column prop="price" label="单价" align="center" />
        <el-table-column prop="amount" label="金额" align="center" />
      </el-table>

      <div class="footer">
        <el-button v-loading="loading" type="primary" @click="handleSubmit">
          提交
        </el-button>
        <el-button plain @click="handleBack"> 返回 </el-button>
      </div>
    </div>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <!-- 内容 -->
      <el-form
        :model="formT"
        ref="queryForm"
        :rules="rules"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="商品编码" prop="matCode">
          <el-select
            filterable
            v-model="formT.matCode"
            placeholder="请选择"
            @change="matCodeChange"
          >
            <el-option
              v-for="item in matCodeOptions"
              :key="item.matCode"
              :label="item.matCode"
              :value="item.matCode"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" prop="matName">
          <el-select
            filterable
            v-model="formT.matName"
            placeholder="请选择"
            @change="matNameChange"
          >
            <el-option
              v-for="item in matCodeOptions"
              :key="item.matCode"
              :label="item.matName"
              :value="item.matName"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品规格" prop="spec">
          <el-input v-model="formT.spec" placeholder="" disabled />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-input v-model="formT.unit" placeholder="" disabled />
        </el-form-item>

        <el-form-item label="总金额" prop="amount">
          <el-input v-model="formT.amount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="数量" prop="matNum">
          <el-input
            v-model="formT.matNum"
            placeholder="请输入数量"
            @input="onInput(0)"
          />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input
            v-model="formT.price"
            placeholder="请输入单价"
            @input="onInput(1)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { fetchCityList } from '@/api/order/order'
import { addMeal, detailMeal, updateMeal } from '@/api/erp/packageManagement'
import { materialList } from '@/api/erp/orderManagement'
import { reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const data = reactive({
  branchOfficeOptions: [],
  disabled: false,
  matCodes: '',
  urls: '',
  matCodeOptions: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  rules: {
    matCode: [{ required: true, message: '请选择商品编码', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入总金额', trigger: 'blur' }]
  },
  ruleT: {
    mealName: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
    orgId: [{ required: true, message: '请选择服务单位', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入套餐价格', trigger: 'blur' }]
  },
  formT: {
    amount: null, //金额
    matCode: '', //物料编码
    matName: '', //物料名称
    matNum: null, //物料数量
    price: null, //物料单价
    spec: '', //规格型号
    unit: '' //物料单位
  },

  dialogVisible: false,
  agreementDialogVisible: false,
  agreementDialogTitle: '',
  dialogTitle: '',
  loading: false,
  total: 0,
  queryParams: {
    amount: '', //套餐金额
    mealName: '', //套餐名称
    orgId: '', //所属服务单位
    mealLines: [] //套餐细项
  }
})

let {
  branchOfficeOptions,
  disabled,
  matCodes,
  urls,
  matCodeOptions,
  single,
  multiple,
  rules,
  ruleT,
  formT,
  dialogVisible,
  agreementDialogVisible,
  agreementDialogTitle,
  dialogTitle,
  loading,
  total,
  queryParams
} = toRefs(data)

init()
function init() {
  getfetchCityList()
  getMaterialList()
  if (route.query.flag == 'updateOrder') {
    loading.value = true
    detailMeal({ id: route.query.id }).then(response => {
      console.log(response)
      queryParams.value = { ...response.data }
      queryParams.value.mealLines = response.data.mealLineList
      console.log(queryParams.value)
      loading.value = false
    })
  }
}

function toDecimal(x) {
  var f = parseFloat(x)
  if (isNaN(f)) {
    return
  }
  f = Math.round(x * 100) / 100
  return f
}
function getSummaries(param) {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map(item => Number(item[column.property]))
    if (column.property == 'amount') {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    }
  })

  return sums
}
// 获取城市列表
function getfetchCityList() {
  loading.value = true
  fetchCityList().then(response => {
    branchOfficeOptions.value = response.data
    loading.value = false
  })
}
async function getMaterialList() {
  materialList({ istatue: 1 }).then(response => {
    matCodeOptions.value = response.rows
    loading.value = false
  })
}
function matNameChange(e) {
  console.log(e)
  for (var i in matCodeOptions.value) {
    if (e == matCodeOptions.value[i].matName) {
      formT.value.matCode = matCodeOptions.value[i].matCode
      formT.value.spec = matCodeOptions.value[i].spec
      formT.value.unit = matCodeOptions.value[i].unit
    }
  }
}
function handleBack() {
  router.push({ path: '/xs/tcgl', query: {} })
}

function handleSubmit() {
  proxy.$refs['queryFormT'].validate(valid => {
    if (valid) {
      queryParams.value.amount = parseFloat(queryParams.value.amount)
      if (route.query.flag == 'updateOrder') {
        updateMeal(queryParams.value).then(res => {
          loading.value = false
          if (res.code === 200) {
            ElMessage.success('操作成功')
            router.push({ path: '/xs/tcgl' })
          } else ElMessage.error(res.msg)
        })
      } else {
        addMeal(queryParams.value).then(res => {
          loading.value = false
          if (res.code === 200) {
            ElMessage.success('操作成功')
            router.push({ path: '/xs/tcgl' })
          } else ElMessage.error(res.msg)
        })
      }
    }
  })
}

// 新增物品
function addGoods(e) {
  dialogVisible.value = true
  dialogTitle.value = '新增套餐内容'
  resetFormT()
}

// 删除物品
function deleteGoods(e) {
  // 确定删除么
  ElMessageBox.confirm('是否确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function () {
    for (var i in matCodes.value) {
      var index = queryParams.value.mealLines.findIndex(item => {
        if (item.matCode == matCodes.value[i]) return true
      })
      queryParams.value.mealLines.splice(index, 1)
    }
    ElMessage.msgSuccess('删除成功')
  })
}

// 确定按钮
function onConfirm() {
  proxy.$refs['queryForm'].validate(valid => {
    formT.value.price = parseFloat(formT.value.price)
    formT.value.matNum = parseInt(formT.value.matNum)
    formT.value.amount = parseFloat(formT.value.amount)
    if (valid) {
      queryParams.value.mealLines.push(formT.value)
      resetFormT()
      dialogVisible.value = false
    }
  })
}

function resetFormT() {
  formT.value = {
    amount: null, //金额
    matCode: '', //物料编码
    matName: '', //物料名称
    matNum: null, //物料数量
    price: null, //物料单价
    spec: '', //规格型号
    unit: '' //物料单位
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  matCodes.value = selection.map(item => item.matCode)
  console.log(matCodes.value)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function matCodeChange(e) {
  console.log(e)
  for (var i in matCodeOptions.value) {
    if (e == matCodeOptions.value[i].matCode) {
      formT.value.matName = matCodeOptions.value[i].matName
      formT.value.spec = matCodeOptions.value[i].spec
      formT.value.unit = matCodeOptions.value[i].unit
    }
  }
}

function onInput(flag) {
  if (flag == 11) {
    // this.queryParams.amount =
    //   parseFloat(this.queryParams.amount)
  } else {
    if (formT.value.amount) {
      if (flag == 0 && formT.value.matNum) {
        formT.value.price =
          parseFloat(formT.value.amount) / parseFloat(formT.value.matNum)
      } else if (flag == 1 && formT.value.price) {
        formT.value.matNum =
          parseFloat(formT.value.amount) / parseFloat(formT.value.price)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.page {
  min-height: calc(100vh - 89px);
  height: calc(100vh - 89px);

  .page-wrapper {
    height: 100%;
    padding: 20px 60px;
    overflow-y: scroll;
  }
}

.header {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 20px;
  height: 50px;
  line-height: 50px;
}

.col .item {
  height: 36px;
  margin-bottom: 20px;
}

.item-label,
.item-value {
  font-size: 12px;
  line-height: 30px;
}

.item-label {
  text-align: right;
  line-height: 36px;
  margin-right: 15px;
}

.footer {
  width: 100%;
  background-color: white;
  text-align: right;
  padding: 10px 30px;
  position: absolute;
  left: 0;
  z-index: 9999;
  right: 0;
  bottom: 0;
  height: 55px;
  border-top: 1px solid lightgray;

  .el-button {
    width: 100px;
  }
}

.table {
  margin: 22px 0;
  .table-label {
    display: inline-block;
    width: 200px;
    text-align: right;
    line-height: 36px;
    padding-right: 12px;
    font-size: 14px;
    color: #606266;
    font-weight: 700;
    vertical-align: top;
  }
  .table-content {
    width: calc(100% - 200px);
    display: inline-block;
  }
}
</style>

<style>
.footer {
  z-index: 999 !important;
}
</style>
